# 高潜用户的年龄对比
# 清除age不合理的值
from matplotlib import pyplot as plt
import pandas as pd


df_usr_ac_firsttime = df_all_buy_ac.groupby(by='user_id').apply(first_time)
# print(df_usr_ac_firsttime)

# 计算时间差
# 计算时间差（保留user_id）
df = pd.merge(
    df_usr_buy_time.to_frame(name='buy_time').reset_index(),
    df_usr_ac_firsttime.to_frame(name='ac_time').reset_index(),
    on='user_id'
)

df["days"] = (pd.to_datetime(df['buy_time']) - pd.to_datetime(df['ac_time'])).dt.days
# print(df)

high_dive = df[df['days'] > 1]
user_table = pd.read_csv('User_table.csv')


user_table_high = pd.merge(user_table,
                           high_dive,
                           on='user_id'
                           )

user_table_high['age'] = user_table_high['age'].apply(lambda x: np.nan if x < 0 or x > 110 else x)
print(user_table_high['age'])
bins = [0, 20, 30, 40, 50, 100]
labels = ['0-20', '21-30', '31-40', '41-50', '50+']
user_table_high['age_group'] = pd.cut(user_table_high['age'], bins=bins, labels=labels)
age_counts = user_table_high['age_group'].value_counts().sort_index()

plt.figure(figsize=(10, 6))
age_counts.plot(kind='bar')
plt.title('高潜客户的年龄段对比')
plt.xlabel('年龄段')
plt.ylabel('用户数量')
plt.xticks(rotation=0)
plt.savefig('高潜用户的年龄对比.png')